package com.dudu.timer;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dudu.bean.ReportWeekBean;
import com.dudu.dao.DailyReportDao;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.utils.DictionaryUtils;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.util.EmailSend;

/**
 * 嘟一下客户周报 统计周期是查询上周五12:00~本周五12:00的数据（报表之间不重复统计数据）。
 * 
 * @author gaoxs 
 * @time 2017-08-03
 */
public class WeeklyReportJob implements Job {
    // log日志
    public static final Logger log = core.util.Logger.getLogger(WeeklyReportJob.class.getName());
    // 数据库连接
    private CoreDao coreDao = CoreDaoInvoke.getInstance();
    // 日报表dao
    private DailyReportDao dailyReportDao = new DailyReportDao();
    // 运营平台地址
    private IOperationPlatformService operationPlatformServiceImpl = new OperationPlatformServiceImpl();

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
	log.info("执行嘟一下客户周报job");
	try {
	    String emailAdressStr = DictionaryUtils.getValueByTypeAndKey("report_email", "weekly"); // 获得日报表接收邮箱
	    if (StringUtils.isNotBlank(emailAdressStr)) {
		StringBuffer content = new StringBuffer(); // 邮件内容
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		String endTime = sdf.format(cal.getTime()) + " 12:00:00";// 格式"2017-08-11 12:00:00"
		cal.add(Calendar.DATE, -7);
		String startTime = sdf.format(cal.getTime()) + " 12:00:00";// 格式"207-08-04 12:00:00"
		// 嘟嘟应用消耗周报
		List<JSONObject> applist = new ArrayList<JSONObject>();
		JSONObject app = new JSONObject();
		app.put("app_key", "99653B0C7EC6897C2F426C0E13A9D66C");
		applist.add(app);
		this.reportWeeklyByApp("嘟嘟应用消耗周报",content, startTime, endTime, applist);
		// ISV应用消耗周报
		applist = this.dailyReportDao.queryActiveAppKeyByTime(coreDao, startTime, endTime,"99653B0C7EC6897C2F426C0E13A9D66C");
		this.reportWeeklyByApp("ISV应用消耗周报",content, startTime, endTime, applist);
		String[] emailAdressArray = emailAdressStr.split(",");

		for (String emailAdress : emailAdressArray) {
		    Thread.sleep(1000 * 10); // 邮件服务器不支持连续发送
		    EmailSend.sendMail(emailAdress, "嘟一下客户周报" + startTime + " - " + endTime, content.toString(), null, null); // 发送邮件
		}

	    } else {
		log.error("未配置周报表接收邮件地址");
	    }
	} catch (Exception ex) {
	    ex.getMessage();
	    log.error("嘟一下周报表error");
	}
    }

    /**
     * 应用消耗周报
     * @param title
     * @param content
     * @param beginTime
     * @param endTime
     * @param appArray
     * @throws UnsupportedEncodingException
     */
    private void reportWeeklyByApp(String title,StringBuffer content, String beginTime, String endTime, List<JSONObject> appArray) {
	if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime) && appArray != null) {
	    List<ReportWeekBean> reportDailyBeanList = new ArrayList<ReportWeekBean>();
	    for (JSONObject appJson : appArray) {
		String appKey = appJson.optString("app_key");
		String isvName = "";// ISV名称
		String appName = "";// 应用名称
		JSONObject object = operationPlatformServiceImpl.queryAppItems("", "", appKey, 1, 2);
		if (object != null) {
		    JSONArray oneAppArray = object.optJSONArray("data");
		    JSONObject oneApp = oneAppArray.getJSONObject(0);
		    isvName = oneApp.optString("isv_name");
		    appName = oneApp.optString("app_name");
		}

		// 1、根据APPKEY获取所有活跃计费账号
		List<JSONObject> dataList = this.dailyReportDao.queryActiveCustaccountByAppAndTime(coreDao, appKey, beginTime, endTime);
		if (dataList != null) {
		    for (JSONObject data : dataList) {
			String custAccount = data.optString("cust_account");
			ReportWeekBean bean = new ReportWeekBean();
			bean.setIsvName(isvName);
			bean.setAppName(appName);
			bean.setCustAccount(custAccount);
			
			JSONObject resourceJSON = operationPlatformServiceImpl.queryResourceAccountSum(appKey, custAccount);
			if (resourceJSON.optString("result").equals("0")) {
			    JSONObject dataJSON = resourceJSON.optJSONObject("data");
			    String custName = dataJSON.optString("cust_name");
			    try {
				custName = URLDecoder.decode(custName, "UTF-8");
			    } catch (UnsupportedEncodingException e) {
				custName = "";
			    }
			    bean.setCustName(custName);
			    JSONArray resource_data = dataJSON.optJSONArray("resource_data");
			    for (int i = 0; i < resource_data.size(); i++) {
				JSONObject resource = resource_data.getJSONObject(i);
				if (resource.optString("product_key").equals("SMMS")) {
				    bean.setSmsBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("ADSMMS")) {
				    bean.setAdSmsBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("VOICE")) {
				    bean.setNoticeBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("IVVR")) {
				    bean.setIvrBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("MPTY")) {
				    bean.setMptyBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("Dial")) {
				    bean.setDailBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("VCAPTCHA")) {
				    bean.setVcaptchaBalance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("VOICE70")) {
				    bean.setVoice70Balance(resource.optString("resuource_num"));
				}
				if (resource.optString("product_key").equals("VOICE140")) {
				    bean.setVoice140Balance(resource.optString("resuource_num"));
				}

			    }// resource_data for
			}
			List<JSONObject> dailyReportlist = this.dailyReportDao.queryTotalTimeByCustaccountAndTime(coreDao, custAccount, beginTime, endTime);
			for (int k = 0; k < dailyReportlist.size(); k++) {
			    JSONObject resource = dailyReportlist.get(k);
			    if (resource.optString("ability_type").equals("SMMS")) {
				bean.setSmsTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("ADSMMS")) {
				bean.setAdSmsTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("VOICE")) {
				bean.setNoticeTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("IVVR")) {
				bean.setIvrTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("MPTY")) {
				bean.setMptyTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("DIAL")) {
				bean.setDailTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("VCAPTCHA")) {
				bean.setVcaptchaTotal(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("VOICE70")) {
				bean.setVoice70Total(resource.optString("total_time"));
			    }
			    if (resource.optString("ability_type").equals("VOICE140")) {
				bean.setVoice140Total(resource.optString("total_time"));
			    }
			}// dailyReportlist for
			reportDailyBeanList.add(bean);
		    }// dataList for
		}

	    }// appArray for

	    Collections.sort(reportDailyBeanList, new Comparator<ReportWeekBean>() {
		@Override
		public int compare(ReportWeekBean o1, ReportWeekBean o2) {
		    Integer count1 = Integer.parseInt(o1.getSmsTotal()) + Integer.parseInt(o1.getAdSmsTotal())
			    + Integer.parseInt(o1.getNoticeTotal())+ Integer.parseInt(o1.getIvrTotal());
		    Integer count2 = Integer.parseInt(o2.getSmsTotal()) + Integer.parseInt(o2.getAdSmsTotal())
			    + Integer.parseInt(o2.getNoticeTotal())+ Integer.parseInt(o2.getIvrTotal());
		    return count2.compareTo(count1);
		}
	    });
	    try {
		String reportDailyContent = getTempleteContent("vm/reportWeeklyCust.vm", reportDailyBeanList,title);
		content.append(reportDailyContent);
	    } catch (Exception e) {
		e.printStackTrace();
		log.error("客户周统计报表渲染模板error");
	    }
	}
    }


    /**
     * 解析模板
     * 
     * @param templete
     * @param list
     * @param title
     * @return
     * @throws Exception
     */
    @SuppressWarnings({ "deprecation", "rawtypes" })
    public static String getTempleteContent(String templete, List list,String title) throws Exception {
	StringWriter writer = null;
	try {
	    URL url = Thread.currentThread().getContextClassLoader().getResource("");
	    String realPath = url.getPath();
	    VelocityEngine ve = new VelocityEngine();
	    Properties p = new Properties();
	    p.put(Velocity.FILE_RESOURCE_LOADER_PATH, URLDecoder.decode(realPath));
	    ve.init(p);
	    Template t = ve.getTemplate(templete, "UTF-8");
	    VelocityContext context = new VelocityContext();
	    context.put("array", list);
	    context.put("title", title);
	    writer = new StringWriter();
	    t.merge(context, writer);
	} catch (Exception e) {
	    log.info("<===获得模板出错==>");
	    e.printStackTrace();
	    throw e;
	}
	return writer.toString();
    }
}
